<?php

namespace CloudTowerDev\F2FPay;

use YunTaIDC\Plugin\PluginBase;

use YunTaIDC\Events\PaySendEvent;
use YunTaIDC\Events\PayReturnEvent;
use YunTaIDC\Events\PayNotifyEvent;

class F2FPay extends PluginBase{
    
    public function onLoad(){

    }

    public function Core(){
        require_once($this->getResourceFolder().'lib/AopClient.php');
        require_once($this->getResourceFolder().'/model/builder/ContentBuilder.php');
        require_once($this->getResourceFolder().'/model/builder/ExtendParams.php');
        require_once($this->getResourceFolder().'/model/builder/GoodsDetail.php');
        require_once($this->getResourceFolder().'/model/builder/RoyaltyDetailInfo.php');
        require_once($this->getResourceFolder().'/model/builder/AlipayTradeRefundContentBuilder.php');
        require_once($this->getResourceFolder().'/model/builder/AlipayTradeQueryContentBuilder.php');
        require_once($this->getResourceFolder().'/model/builder/AlipayTradePrecreateContentBuilder.php');
        require_once($this->getResourceFolder().'/model/request/AlipayFundTransToaccountTransferRequest.php');
        require_once($this->getResourceFolder().'/model/request/AlipaySystemOauthTokenRequest.php');
        require_once($this->getResourceFolder().'/model/request/AlipayTradePrecreateRequest.php');
        require_once($this->getResourceFolder().'/model/request/AlipayTradeQueryRequest.php');
        require_once($this->getResourceFolder().'/model/request/AlipayTradeRefundRequest.php');
        require_once($this->getResourceFolder().'/model/request/AlipayUserInfoShareRequest.php');
        require_once($this->getResourceFolder().'/model/result/AlipayF2FPrecreateResult.php');
        require_once($this->getResourceFolder().'/model/result/AlipayF2FQueryResult.php');
        require_once($this->getResourceFolder().'/model/result/AlipayF2FRefundResult.php');
        require_once($this->getResourceFolder().'AlipayTradeService.php');
        require_once($this->getResourceFolder().'AlipayOauthService.php');
    }
    
    public function onPaySend(PaySendEvent $Event){
        // echo '发起成功！<br>';
        // echo '金额：' . $Event->getOrder()->getMoney().'<br>';
        // echo '同步返回地址：http://'.$_SERVER['HTTP_HOST'].'/index.php?p=Pay&a=Return&Gateway='.$Event->getGateway()->getId().'&orderid='.$Event->getOrder()->getOrderId().'<br>';
        // echo '异步返回地址：http://'.$_SERVER['HTTP_HOST'].'/index.php?p=Pay&a=Notify&Gateway='.$Event->getGateway()->getId().'&orderid='.$Event->getOrder()->getOrderId();
        $this->Core();
        $alipay_config = $Event->getGateway()->getConfigOption();
        $alipay_config['charset'] = 'utf-8';
        $alipay_config['gatewayUrl'] = 'https://openapi.alipay.com/gateway.do';
        $alipay_config['notify_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/index.php?p=Pay&a=Notify&Gateway='.$Event->getGateway()->getId();
        $qrPayRequestBuilder = new AlipayTradePrecreateContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($Event->getOrder()->getOrderId());
        $qrPayRequestBuilder->setTotalAmount($Event->getOrder()->getMoney());
        $qrPayRequestBuilder->setSubject('onlinepay-'.time());
        $qrPay = new AlipayTradeService($alipay_config);
        $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);$status = $qrPayResult->getTradeStatus();
        $response = $qrPayResult->getResponse();
        if($status == 'SUCCESS'){
            $code_url = $response->qr_code;
            $content = file_get_contents($this->getResourceFolder().'pay.html');
            $content = str_replace('[template]', $this->getResourceFolder(), $content);
            $content = str_replace('[code_url]', $code_url, $content);
            $content = str_replace('[orderid]', $Event->getOrder()->getOrderId(), $content);
            $content = str_replace('[orderid]', $Event->getOrder()->getMoney(), $content);
            echo $content;
        }elseif($status == 'FAILED'){
            // sysmsg('支付宝创建订单二维码失败！['.$response->sub_code.']'.$response->sub_msg);
            @header("Location: ./index.php?p=Clientarea&a=Msg&msg=支付宝创建订单二维码失败");
            exit;
        }else{
            // print_r($response);
            // sysmsg('系统异常，状态未知！');
            @header("Location: ./index.php?p=Clientarea&a=Msg&msg=系统异常，状态未知！");
            exit;
        }
    }
    
    public function onPayReturn(PayReturnEvent $event){
        
    }
    
    public function onPayNotify(PayNotifyEvent $event){
        $$alipay_config = $event->getGateway()->getConfigOption();
        $alipay_config['charset'] = 'utf-8';
        $alipay_config['gatewayUrl'] = 'https://openapi.alipay.com/gateway.do';
        $alipay_config['notify_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/index.php?p=Pay&a=Notify&Gateway='.$Event->getGateway()->getId();
        $alipaySevice = new AlipayTradeService($alipay_config); 
        //$alipaySevice->writeLog(var_export($_POST,true));
        $verify_result = $alipaySevice->check($_POST);

        if($verify_result) {//验证成功
            //商户订单号

            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号

            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];

            //买家支付宝
            $buyer_id = $_POST['buyer_id'];

            return array(
                'status' => 'success',
                'Orderid' => $out_trade_no,
            );
        }
        else {
            return array(
                'status' => 'fail',
            );
        }
    }
    
    public function GatewayConfig(){
        return array(
            'sign_type' => array('label' => '签名方式', 'placeholder' => 'RSA2', 'type' => 'text'),
            'alipay_public_key' => array('label' => '支付宝公钥', 'placeholder' => '支付宝公钥', 'type' => 'textarea'),
            'merchant_private_key' => array('label' => '商户私钥', 'placeholder' => '商户私钥', 'type' => 'textarea'),
            'method' => array('label' => '对接数据提交方式（第一种不行换第二种）', 'option' => array('POST' => 'POST', 'GET' => 'GET',), 'type' => 'select'),
            'app_id' => array('label' => '应用ID', 'placeholder' => '应用ID', 'type' => 'number'),
        );
    }
    
}

?>